<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" align-center :width="1700" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true">
		<el-form :model="form" class="fullHeight" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="100" label-position="right" style="height:700px;overflow:auto;overflow-x:hidden;">
			<el-row :gutter="1">
				<el-col :span="5">
					<el-form-item label="客户" prop="customer_id">
						<div style="display:flex;width:100%">
							<el-input v-model="customer_name" placeholder="请选择客户" @click="checkCustom" readonly></el-input>
							<el-button type="info" icon="el-icon-Close" style="margin-left:5px" @click="clearCustom"></el-button>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="开单日期" prop="open_single">
						<el-date-picker v-model="form.open_single" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="报价交期" prop="deliver_date">
						<el-date-picker v-model="form.deliver_date" type="date" placeholder="请选择交期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
					</el-form-item>
				</el-col>
                <el-col :span="4">
                    <el-form-item label="是否开票" prop="is_ticket">
                        <el-switch v-model="form.is_ticket" :active-value="2" :inactive-value="1"></el-switch>
					</el-form-item>
				</el-col>
                <el-col :span="5">
                    <el-form-item label="报价金额" prop="total_price">
                        <el-input v-model="form.total_price" placeholder="报价金额" readonly></el-input>
                    </el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="1">
				<el-col :span="12">
					<el-form-item label="备注" prop="remark">
						<el-input v-model="form.remark" placeholder="备注" type="textarea" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="附件" prop="enclosure">
						<sc-upload-file v-model="form.enclosure" :is_same_name="1">
							<el-button type="primary" icon="el-icon-upload">选择文件</el-button>
						</sc-upload-file>
					</el-form-item>
				</el-col>
			</el-row>
			<el-col :span="24">
				<el-form-item label="商品清单" prop="order_detail">
                    <div class="flex">
                        <div style="display:flex;align-items:center;">
                            <el-button type="primary" size="small" icon="el-icon-plus" @click="checkGoods">选择商品</el-button>
                            <sc-import-button :auth="'goods.impoet'" :apiObj="importObj" :size="'small'" :base="base + '/file_templets/temples_bom.xls'" @importSuccess="importSuccess"></sc-import-button>
                        </div>
                        <el-form-item label="扫码录入">
                            <div style="display:flex;width:100%">
                                <el-input v-model="bar_code" ref="barInput" v-if="barInput == 0" @input="handInput"></el-input>
                                <el-switch v-model="barInput" :active-value="0" :inactive-value="1" @change="barChange"></el-switch>
                            </div>
                        </el-form-item>
                    </div>
					<sc-form-table ref="table" v-model="form.order_detail" placeholder="暂无数据" @tableDel="deleteTable" hide-Add height="500" show-summary>
						<el-table-column label="商品名称" align="center">
                            <template #default="scope">
                                {{scope.row.goods_name}}
                            </template>
                        </el-table-column>
						<el-table-column label="商品编码" align="center">
                            <template #default="scope">
                                {{scope.row.goods_code}}
                            </template>
                        </el-table-column>
						<el-table-column label="商品图片" align="center">
							<template #default="scope">
								<el-image v-if="scope.row.goods_image" style="width: 30px; height: 30px; border-radius: 5px;" :src="scope.row.goods_image" :preview-src-list="[scope.row.goods_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
							</template>
						</el-table-column>
						<el-table-column label="规格型号" align="center">
                            <template #default="scope">
                                {{scope.row.goods_spec}}
                            </template>
                        </el-table-column>
						<el-table-column label="分类" align="center">
                            <template #default="scope">
                                {{scope.row.cate_name}}
                            </template>
                        </el-table-column>
						<el-table-column label="单位" align="center">
                            <template #default="scope">
                                {{scope.row.unit_name}}
                            </template>
                        </el-table-column>
						<el-table-column label="销售数量" prop="sale_num" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.sale_num" placeholder="销售数量" @input="totalCompute" @focus="onFocus($event)"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="未税单价" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.price" placeholder="未税单价" @input="totalCompute" @focus="onFocus($event)"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="含税单价" align="center">
							<template #default="scope">
                                <el-input v-model="scope.row.tax_price" placeholder="含税单价" @input="taxCompute" @focus="onFocus($event)"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="税率" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.tax_rate" placeholder="税率" @input="taxChange" @focus="onFocus($event)"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="税额" align="center">
							<template #default="scope">
								{{ scope.row.tax_rate && scope.row.price && scope.row.sale_num ?
								(((1 + (Number(scope.row.tax_rate) / 100)) * Number(scope.row.price)* Number(scope.row.sale_num)) - ((Number(scope.row.price) * Number(scope.row.sale_num)))).toFixed(2) : 0 }}
							</template>
						</el-table-column>
						<el-table-column label="未税合计" prop="amount" align="center"></el-table-column>
						<el-table-column label="含税合计" prop="total_price" align="center"></el-table-column>
						<el-table-column label="备注" prop="remark" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.remark" placeholder="备注"></el-input>
							</template>
						</el-table-column>
					</sc-form-table>
				</el-form-item>
			</el-col>
		</el-form>
        <template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
			<el-button v-if="mode == 'add' || mode == 'copy'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
		</template>
		<!-- <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
			<el-button v-if="mode == 'add' || mode == 'copy'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
		</el-footer> -->
	</el-dialog>
	<select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods>
	<client-list v-if="dialog.client" ref="clientDialog" @success="clientUpdate" @closed="dialog.client=false"></client-list>
	<setting-money v-if="dialog.setting" ref="settingDialog" @success="handleSetting" @closed="dialog.setting=false"></setting-money>
</template>

<script>
import ClientList from '../client/list/clientList.vue';
import selectGoods from '../../goods/info/selectGoods.vue';
import settingMoney from "@/views/procure/order/settingMoney.vue";
import config from '@/config'

export default {
	components: {settingMoney, selectGoods, ClientList},
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增销售订单',
				copy: '新增销售订单',
				edit: '编辑销售订单',
				show: '查看销售订单'
			},
			visible: false,
			isSaveing: false,
			//表单数据
			form: {
				id: "",
				customer_id: "",
				contacts: "",
				open_single: this.moment().format('YYYY-MM-DD'),
				deliver_date: "",
				// is_tax: "",
				is_ticket: 1,
                is_offer: 0,
                source: 1,
				ship_name: "",
				send_date: "",
				send_goods_no: "",
				remark: "",
				enclosure: "",
				status: "",
				order_detail: [],
				total_price: "",
				pay_price: 0,
				settlement_id: "",
				is_stages: 0,
				stages_all: [],
				is_check: 0,
				has_discount: '',
				total_amount: 0,
				discount_num: null
			},
			//验证规则
			rules: {
				customer_id: [{required: true, message: '请选择客户'}],
			},
			customer_name: "",
			contactList: [],
			addTemplate: {},
			dialog: {
				goods: false,
				client: false,
			},
			cateProps: {
				value: "id",
				label: "cate_name",
				checkStrictly: true
			},
			accountList: [],
            taxObj: {},
            barInput: 1,
            bar_code: "",
            importObj: this.$API.goods.bom.import,
            base: config.API_URL
		}
	},
    created() {
        this.handInput = this.debounce(this.handInput, 500);
	},
	mounted() {
		this.getAccount() // 账号
        this.getIsTax()
	},
	methods: {
        // 防抖
        debounce(func, delay){
            let timeoutId;
            return function(...args) {
                if (timeoutId) {
                    clearTimeout(timeoutId);
                }
                timeoutId = setTimeout(() => {
                    func.apply(this, args);
                }, delay);
            };
        },
        handInput(e){
            this.getProduct(e)
        },
        async getProduct(e){
            if(!e){
                return
            }
            var res = await this.$API.goods.goods.search.get({ bar_code:e });
            let exist = this.common.isExist(res.data.id, this.form.order_detail, 'goods_id')
            if (exist) {
                this.form.order_detail.map(item1=>{
                    if(item1.goods_id == res.data.id){
                        item1.sale_num += 1
                    }
                })
            }else{
                if(res.data.id){
                    let array = []
                    array.push({
                        goods_id: res.data.id,
                        goods_name: res.data.goods_name,
                        cate_name: res.data.cate && res.data.cate.cate_name,
                        unit_name: res.data.unit && res.data.unit.unit_name,
                        goods_code: res.data.goods_code,
                        goods_spec: res.data.goods_spec,
                        goods_image: res.data.goods_image,
                        tax_rate: this.taxObj.number,
                        sale_num: 1,
                        price: res.data.factory_price,
                    })
                    this.form.order_detail = [...this.form.order_detail, ...array]
                    this.totalCompute()
                }
            }
            this.bar_code = ""
        },
        importSuccess(res){
            let array = []
            res.bom_child.map(item=>{
                array.push({
					goods_id: item.goods_id,
                    goods_name:item.goods && item.goods.goods_name,
					cate_name: item.goods && item.goods.cate && item.goods.cate.cate_name,
					unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
                    goods_code:item.goods && item.goods.goods_code,
                    goods_spec:item.goods && item.goods.goods_spec,
					tax_rate: this.taxObj.number,
					sale_num: item.number,
					price: item.goods && item.goods.factory_price,
                })
            })
            this.form.order_detail = array
            this.totalCompute()
        },
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit(e) {
			this.form.is_check = e
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = [];
					if (this.form.id) {
						res = await this.$API.contract.contract.edit.post(this.form);
					} else {
						res = await this.$API.contract.contract.add.post(this.form);
					}
					this.isSaveing = false;
					if (res.code == 1) {
						this.visible = false;
						this.$emit('success', this.form, this.mode)
						this.$message.success("操作成功")
					} else {
						this.$alert(res.message, "提示", {type: 'error'})
					}
				} else {
					return false;
				}
			})
		},
		//表单注入数据
		async setData(data, value) {
			var res = await this.$API.contract.contract.detail.get({id: data.id});
			if (!value) {
				this.form.id = data.id
				this.form.contract_code = data.contract_code
			}
			this.form.customer_id = res.data.customer_id
			this.customer_name = data.customer.customer_name
			this.getContact(this.form.customer_id)
			this.form.contacts = res.data.contacts
			this.form.open_single = res.data.open_single
			this.form.deliver_date = res.data.deliver_date
			// this.form.is_tax = res.data.is_tax == 0 ? '' : res.data.is_tax
			this.form.is_ticket = res.data.is_ticket
			this.form.ship_name = res.data.ship_name
			this.form.send_date = res.data.send_date
			this.form.send_goods_no = res.data.send_goods_no
			this.form.remark = res.data.remark
            if(res.data.enclosure) {
                this.form.enclosure = res.data.enclosure
            }
			// this.form.status = res.data.status
			this.form.total_price = res.data.total_price
			this.form.pay_price = res.data.pay_price
			this.form.settlement_id = res.data.settlement_id
			// this.form.contract_status = res.data.contract_status
			this.form.has_discount = res.data.has_discount
			this.form.discount_num = res.data.discount_num
			this.form.total_amount = res.data.total_amount
			let array = []
			res.data.order_detail.map(item => {
				let data = {
					goods_id: item.goods_id,
					supplier: item.supplier,
					remark: item.remark,
					goods_name: item.goods && item.goods.goods_name,
					goods_image: item.goods && item.goods.goods_image,
					unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
					cate_name: item.goods && item.goods.cate && item.goods.cate.cate_name,
					goods_code: item.goods && item.goods.goods_code,
					goods_spec: item.goods && item.goods.goods_spec,
                    sale_num: item.sale_num,
					price: item.price,
                    amount: (Number(item.sale_num) * Number(item.price)).toFixed(2),
					tax_price: item.tax_price,
					total_price: item.total_price,
					tax_rate: item.tax_rate,
				}
				if (!value) {
					data.id = item.id
				}
				array.push(data)
			})
			this.form.order_detail = array
			this.form.is_stages = res.data.is_stages
			if (res.data.by_stages && res.data.by_stages.length > 0) {
				res.data.by_stages.map(item => {
					let data = {
						collect_date: item.collect_date,
						collect_rate: item.collect_rate,
						money: item.money,
						remark: item.remark,
						stages_number: item.stages_number
					}
					if (!value) {
						data.id = item.id
					}
					this.form.stages_all.push(data)
				})
			}
		},
		onFocus(event) {
			event.target.select();
		},
		checkCustom() {
			this.dialog.client = true
			this.$nextTick(() => {
				this.$refs.clientDialog.open('add')
			})
		},
		clientUpdate(data) {
			console.log(data);
			this.form.customer_id = data.id
			this.customer_name = data.customer_name
			this.getContact(data.id)
		},
		async getContact(e) {
			var res = await this.$API.client.client.detail.get({id: e});
			this.contactList = res.data.customer
		},
		clearCustom() {
			this.form.customer_id = ""
			this.form.contacts = ""
			this.customer_name = ""
			this.contactList = []
		},
		// 选择商品
		checkGoods(e) {
			this.dialog.goods = true
			this.$nextTick(() => {
				this.$refs.goodsDialog.open('add').setData(e)
			})
		},
		goodsUpdate(data) {
			let array = []
			data.map((item) => {
                let exist = this.common.isExist(item.id, this.form.order_detail, 'goods_id')
                if (exist) {
                    return
                }
				array.push({
					goods_id: item.id,
					goods_name: item.goods_name,
					goods_image: item.goods_image,
					cate_name: item.cate_name,
					unit_name: item.unit_name,
					goods_code: item.goods_code,
					goods_spec: item.goods_spec,
					tax_rate: this.taxObj.number,
					sale_num: 1,
					price: item.factory_price,
				})
			})
			this.form.order_detail = [...this.form.order_detail, ...array]
			this.totalCompute()
		},
		/**表格商品删除事件*/
		deleteTable() {
			this.totalCompute()
		},
		/**折扣方式选择事件*/
		hasChange() {
			this.form.discount_num = null
			this.totalCompute()
		},
		/**折扣率 折扣额 输入事件*/
		discountChange() {
			this.totalCompute()
		},
		/**计算总金额*/
		totalCompute() {
			let count_price = 0
			this.form.total_price = 0
			this.form.order_detail.map(item => {
				if (item.price && item.sale_num) {
					item.total_price = (Number(item.sale_num) * Number(item.price) * (1 + (Number(item.tax_rate) / 100))).toFixed(2)
                    item.amount = (Number(item.sale_num) * Number(item.price)).toFixed(2)
                    item.tax_price = ((1 + (Number(item.tax_rate) / 100)) * Number(item.price)).toFixed(2)
					count_price = Number(count_price) + Number(item.total_price)
				}
			})
			this.form.total_price = count_price.toFixed(2)
			if (this.form.has_discount == 1) {
				this.form.total_amount = (Number(this.form.total_price) - (Number(this.form.total_price) * (Number(this.form.discount_num) / 100))).toFixed(2)
			} else if (this.form.has_discount == 2) {
				this.form.total_amount = (Number(this.form.total_price) - Number(this.form.discount_num)).toFixed(2)
			} else {
				this.form.total_amount = this.form.total_price
			}
			this.form.stages_all = []
		},
        taxCompute(){
            let count_price = 0
			this.form.total_price = 0
			this.form.order_detail.map(item => {
				if (item.price && item.sale_num) {
                    item.price = (item.tax_price / (1 + (Number(item.tax_rate) / 100))).toFixed(2)
                    item.amount = (Number(item.sale_num) * Number(item.price)).toFixed(2),
					item.total_price = (Number(item.sale_num) * Number(item.tax_price)).toFixed(2)
					count_price = Number(count_price) + Number(item.total_price)
				}
			})
			this.form.total_price = count_price.toFixed(2)
			if (this.form.has_discount == 1) {
				this.form.total_amount = (Number(this.form.total_price) - (Number(this.form.total_price) * (Number(this.form.discount_num) / 100))).toFixed(2)
			} else if (this.form.has_discount == 2) {
				this.form.total_amount = (Number(this.form.total_price) - Number(this.form.discount_num)).toFixed(2)
			} else {
				this.form.total_amount = this.form.total_price
			}
			this.form.stages_all = []
        },
        taxChange(){
            let count_price = 0
			this.form.total_price = 0
			this.form.order_detail.map(item => {
				if (item.price && item.sale_num) {
                    item.amount = (Number(item.sale_num) * Number(item.price)).toFixed(2),
                    item.tax_price = ((1 + (Number(item.tax_rate) / 100)) * Number(item.price)).toFixed(2)
					item.total_price = (Number(item.sale_num) * Number(item.price) * (1 + (Number(item.tax_rate) / 100))).toFixed(2)
					count_price = Number(count_price) + Number(item.total_price)
				}
			})
			this.form.total_price = count_price.toFixed(2)
			if (this.form.has_discount == 1) {
				this.form.total_amount = (Number(this.form.total_price) - (Number(this.form.total_price) * (Number(this.form.discount_num) / 100))).toFixed(2)
			} else if (this.form.has_discount == 2) {
				this.form.total_amount = (Number(this.form.total_price) - Number(this.form.discount_num)).toFixed(2)
			} else {
				this.form.total_amount = this.form.total_price
			}
			this.form.stages_all = []
        },
		// 账户
		async getAccount() {
			var res = await this.$API.finance.account.all.get();
			this.accountList = res.data;
		},
        async getIsTax() {
			var res = await this.$API.setting.getSaleTax.get();
            this.taxObj = res.data
		},
        /**分期设置金额成功事件*/
		handleSetting(data) {
			this.form.stages_all = data
		},
		/**设置分期按钮点击*/
		openStage() {
			if (this.form.total_amount <= 0) {
				this.$message.error("当前金额为0！")
				return;
			}
			this.dialog.setting = true
			this.$nextTick(() => {
				this.$refs.settingDialog.open('add').setData(this.form)
			})
		},
		/**设置分期*/
		stagesChange() {
			console.log(this.form.is_stages)
			if (this.form.is_stages == 1) {
				this.form.pay_price = 0
			} else {
				// this.form.pay_price = this.form.total_amount
				this.form.stages_all = []
			}
		},
        barChange(e){
            if(e == 0){
                this.$nextTick(()=>{
                    this.$refs.barInput.focus()
                })
            }
        },
	}
}
</script>

<style>
.fullHeight {
	max-height: 1000px!important;
	overflow: hidden;
	overflow-y: auto;
}
.flex{
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding-right: 35px;
}
</style>
